load "$NCARG_ROOT/lib/ncarg/nclscripts/csm/gsn_code.ncl"
load "$NCARG_ROOT/lib/ncarg/nclscripts/csm/gsn_csm.ncl"
load "$NCARG_ROOT/lib/ncarg/nclscripts/csm/contributed.ncl"

begin
;======================================input==============================
  fread   = addfile("data/SST/ERSST_v5/ersst.v5.185401-202012.nc","r")
  YYYYMM  = cd_calendar(fread->time,1)
  tStrt   = ind(YYYYMM.eq.195101)
  tLast   = ind(YYYYMM.eq.202012)
  sst0    = fread3->sst(tStrt:tLast,0,:,:)
  sst0    = where(sst0.eq.-1000,sst0@_FillValue,sst0)
  sst0    = where(sst0.eq.-1.8,sst0@_FillValue,sst0)
  sst     = month_to_season(sst0,"JJA")
  sst     = (sst0(5::12,:,:)+sst0(6::12,:,:)+sst0(7::12,:,:)+sst0(8::12,:,:))/4.
  delete(YYYYMM)
;============================external forcing signal========================
  model = (/"ACCESS-CM2","ACCESS-ESM1-5","BCC-CSM2-MR","CNRM-CM6-1","GFDL-ESM4",\
            "HadGEM3-GC31-LL","IPSL-CM6A-LR","MIROC6","MRI-ESM2-0","NorESM2-LM"/);

  tm = new((/10,70/),"float")

  do i=0,9
    print(model(i))

    fread   = addfile("data/ts/ts_Amon_"+model(i)+"_historical-ssp245_mme_195001-210012.nc","r")
    YYYYMM  = cd_calendar(fread->time,1)
    tStrt   = ind(YYYYMM.eq.195101)
    tLast   = ind(YYYYMM.eq.202012)
    ts      = month_to_annual(fread->ts(tStrt:tLast,:,:),1)

    rad      = 4.*atan(1.0)/180.0 
    clat     = ts&lat
    clat     = cos(clat*rad)
    clat!0   = "lat"
    clat&lat = ts&lat

    tm(i,:) = wgt_areaave_Wrap(ts,clat,1.0,0)

    delete([/ts,clat,YYYYMM/])

  end do 

  tm = tm-conform(tm,dim_avg_n_Wrap(tm(:,45:64),1),0)

  GM = dim_avg_n_Wrap(tm,0)
;============================Removing externally-forced response===================

  A      = regCoef_n(GM,sst,0,0)
  AX     = conform(sst,GM,0)*conform(sst,A,(/1,2/))
  sst    = sst-AX

end 